import {
  message, udp, useAsyncEffect, useRefCallback, useRefState,
} from '@cscec/udp-ui';
import React, { ReactNode } from 'react';
import { CSSProperties } from 'react';

export const containerStyle: CSSProperties = {
  borderRadius: 8,
  backgroundColor: '#fff',
};

export const titleStyle: CSSProperties = {
  position: 'relative',
  display: 'flex',
  alignItems: 'center',
  minHeight: 48,
  fontSize: 16,
  marginTop: -24,
  fontWeight: 600,
  color: 'rgba(0, 0, 0, 0.85)',
  borderBottom: '1px solid rgba(0, 0, 0, 0.06)'
};

export function useList<T>({ env, source, defaultData }: { env: any, source?: any, defaultData?: T[] }) {
  const [page, setPage] = useRefState({ pageNum: 1, pageSize: 8, pageIndex: 1 });
  const [state, setState] = useRefState<{ loading: boolean; list: T[]; total: number; pagination: any }>({
    loading: false, list: [], total: 0, pagination: false
  });

  const onChange = (pageNum: number, pageSize: number) => {
    setPage({ pageNum, pageSize, pageIndex: pageNum });
  };

  useAsyncEffect(async () => {
    if (!source) {
      const d = defaultData || [];
      setState({
        loading: false, list: d, total: d.length, pagination: false,
      });
      return;
    }
    setState({ loading: true });
    let params = source;
    if (udp.isString(params)) {
      params = { url: params, data: page };
    } else {
      params.data = { ...params.data, ...page };
    }
    const { status, msg, data } = await env.fetcher(params);
    if (status === 0) {
      const hasPagination = data.hasOwnProperty('pageSize') && data.hasOwnProperty('pageNum');
      const list = data.list ?? data ?? [];
      setState({
        loading: false,
        pagination: (hasPagination ? {
          size: 'small', hideOnSinglePage: true, pageSize: page.pageSize, current: page.pageNum, total: data.total, onChange,
        } : false),
        list,
        total: data.total ?? list.length,
      });
    } else {
      message.error(msg);
      setState({
        loading: false, list: [], total: 0, pagination: false,
      });
    }
  }, [source, page]);

  const reload = useRefCallback(() => {
    setPage({ pageIndex: 1, pageNum: 1 });
  });

  return { ...state, reload };
}

export function PortalTitle(props: { children: ReactNode }) {
  return <div style={titleStyle} className='udp-portal-tip'>{props.children}</div>;
}